package com.iot.server.config.shiro;

import com.iot.core.exception.BDException;
import com.iot.core.utils.MD5Utils;
import com.iot.server.domain.SysRoleDO;
import com.iot.server.domain.SysUserDO;
import com.iot.server.service.RoleService;
import com.iot.server.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author SPPan
 */
public class MyRealm extends AuthorizingRealm {
    @Autowired
    @Lazy
    private UserService userService;
    @Autowired
    @Lazy
    private RoleService roleService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        SysUserDO user = (SysUserDO) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        Set<String> shiroPermissions = new HashSet<>();
        Set<String> roleSet = new HashSet<String>();
        List<SysRoleDO> roleList = roleService.selectRolesByUserId(user.getUserId());
        roleList.forEach(r -> roleSet.add(r.getRoleSign()));
        authorizationInfo.setRoles(roleSet);
        authorizationInfo.setStringPermissions(shiroPermissions);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken token) throws AuthenticationException {
        String userId = (String) token.getPrincipal();
        SysUserDO user = userService.selectUserById(userId);
        String password = new String((char[]) token.getCredentials());
        // 账号不存在
        if (user == null) {
            throw new BDException("账号不存在");
        }
        // 密码错误
        if (!MD5Utils.encrypt(userId, password).equals(user.getPassword())) {
            throw new BDException("密码不正确");
        }
        // 账号锁定
        if (user.getLocked().equals("-1")) {
            throw new BDException("账号已被锁定,请联系管理员");
        }

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
        return info;
    }
    /**
     * 重写方法,清除当前用户的的 授权缓存
     *
     * @param principals
     */
    @Override
    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }
    /**
     * 重写方法，清除当前用户的 认证缓存
     *
     * @param principals
     */
    @Override
    public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
        super.clearCachedAuthenticationInfo(principals);
    }
    @Override
    public void clearCache(PrincipalCollection principals) {
        super.clearCache(principals);
    }

}
